﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;
using Core.Attributes;

namespace Core
{
    public class ParserLoader
    {
        private List<IParser<Result>> _parsers ;
        private string configFile;

        public ParserLoader(string config)
        {
            configFile = config;
        }

        public List<IParser<Result>> GetParsers()
        {
            if (_parsers == null)
            {
                _parsers = LoadParsers();
            }
            return _parsers;
        }

        public List<IParser<Result>> LoadParsers()
        {
            var x = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo directory = new DirectoryInfo(x);

            var files = directory.EnumerateFiles();
            var newFiles = files.Where(f => (f.Extension == ".dll" && f.Name.Contains("CVSParser")));

            var parsers = new List<IParser<Result>>();

            foreach (FileInfo file in newFiles)
            {
                var parserAssembly = Assembly.LoadFile(file.FullName);
                var dsd = parserAssembly
                    .GetTypes();
                var pTypes = parserAssembly
                    .GetTypes()
                    .Where(type => type.GetInterface(typeof(IParser<Result>).Name) != null)
                        .ToList();

                XElement element = null;
                foreach (var type in pTypes)
                {
                    if (File.Exists(configFile))
                    {
                        var document = XDocument.Load(configFile);

                        element = document.XPathSelectElement("//" + type.Name);
                    }
                    var attribute = type.GetCustomAttribute<ParserConfigAttribute>();

                    if (attribute == null)
                        throw new Exception("asdasdas");

                    var config = Activator.CreateInstance(attribute.ConfigType);
                    XmlConfigurator.Configure(config, element);

                    var obj = (IParser<Result>)Activator.CreateInstance(type);
                    obj.ConvetMyConfig(config);
                    parsers.Add(obj);
                }
            }
            return parsers;
        }
    }
}
